# 营养顾问建议管理的视图文件
from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator
from django.db.models import Q
from datetime import datetime

from myadmin.models import NutritionistAdvice, Users

# 营养顾问建议管理
def index(request, pIndex=1):
    """建议列表页（查看功能）"""
    # 获取所有建议，预加载关联的用户和营养顾问
    alist = NutritionistAdvice.objects.select_related('user', 'nutritionist').all()
    mywhere = []
    
    # 排序处理
    sort = request.GET.get('sort', None)
    order = request.GET.get('order', 'asc')
    if sort:
        if order == 'desc':
            sort = f'-{sort}'
        try:
            alist = alist.order_by(sort)
            mywhere.extend([f'sort={sort.replace("-", "")}', f'order={order}'])
        except:
            pass
    
    # 搜索处理（支持搜索用户、营养顾问、建议内容）
    kw = request.GET.get("keyword", None)
    if kw:
        alist = alist.filter(
            Q(user__username__contains=kw) | 
            Q(nutritionist__username__contains=kw) |
            Q(advice_content__contains=kw)
        )
        mywhere.append(f'keyword={kw}')
    
    # 状态筛选
    status = request.GET.get('status', '')
    if status:
        alist = alist.filter(status=status)
        mywhere.append(f'status={status}')
    
    # 日期筛选（建议日期）
    date_str = request.GET.get('advice_date', '')
    if date_str:
        try:
            advice_date = datetime.strptime(date_str, '%Y-%m-%d').date()
            alist = alist.filter(advice_date=advice_date)
            mywhere.append(f'advice_date={date_str}')
        except ValueError:
            pass  # 日期格式错误则忽略筛选
    
    # 分页处理
    pIndex = int(pIndex)
    page = Paginator(alist, 10)  # 每页10条记录
    maxpages = page.num_pages
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)
    plist = page.page_range
    
    # 准备状态选项用于筛选框
    status_choices = NutritionistAdvice.STATUS_CHOICES
    
    context = {
        "advicelist": list2,
        'status_choices': status_choices,
        'plist': plist,
        'pIndex': pIndex,
        'maxpages': maxpages,
        'mywhere': mywhere,
        'selected_status': status,
        'selected_date': date_str
    }
    return render(request, "myadmin/nutritionistadvice/index.html", context)

def feedback(request, aid=0):
    """加载反馈表单"""
    try:
        ob = NutritionistAdvice.objects.select_related('user', 'nutritionist').get(advice_id=aid)
        context = {'advice': ob}
        return render(request, "myadmin/nutritionistadvice/feedback.html", context)
    except NutritionistAdvice.DoesNotExist:
        context = {'info': "没有找到要反馈的建议！"}
    except Exception as err:
        print(err)
        context = {'info': "加载反馈表单失败！"}
    return render(request, "myadmin/info.html", context)

def do_feedback(request, aid=0):
    """执行反馈操作（更新状态）"""
    try:
        # 获取建议对象
        ob = NutritionistAdvice.objects.get(advice_id=aid)
        
        # 获取新状态（必须是已反馈）
        new_status = request.POST.get('status', '')
        if new_status not in [choice[0] for choice in NutritionistAdvice.STATUS_CHOICES]:
            raise ValueError("无效的状态值！")
        
        # 反馈内容可选，但状态为已反馈时建议填写
        feedback_content = request.POST.get('feedback_content', '').strip()
        
        # 更新状态
        ob.status = new_status
        ob.save()
        
        context = {'info': "反馈处理成功！"}
    except NutritionistAdvice.DoesNotExist:
        context = {'info': "反馈失败：建议不存在！"}
    except ValueError as e:
        context = {'info': f"反馈失败：{str(e)}"}
    except Exception as err:
        print(f"反馈处理错误: {err}")
        context = {'info': "反馈处理失败：发生未知错误！"}
    return render(request, "myadmin/info.html", context)